import React, { useState, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { ArrowCornerLeft, More } from '@nutui/icons-react'
import { Popup, Cell, Input, Button, Toast, Image, Sticky, Popover, changelayer, Grid, } from 'react-vant';
import IconFont from './Tubiao';
import axios from 'axios';
import './css/xx.scss'
import { io } from "socket.io-client";
import { BackTop } from '@nutui/nutui-react';
export default function Xx() {
  let navigate = useNavigate()
  axios.defaults.baseURL = 'http://123.57.180.216:3000/'
  const [text, setText] = useState('')
  const [messages, setMessages] = useState([])
  const user = JSON.parse(sessionStorage.getItem("user"))
  const friend = JSON.parse(sessionStorage.getItem("friend"))
  let [search, setSearch] = useSearchParams()
  const [isVisible, setIsVisible] = useState(false)
  let [list1, setList1] = useState([])


  const [emojilist, setemojilist] = useState([ // emoji 数据列表
    { id: 1, emoji: '😀' },
    { id: 2, emoji: '😂' },
    { id: 3, emoji: '🥂' },
    { id: 4, emoji: '🤩' },
    { id: 5, emoji: '👿' },
    { id: 6, emoji: '😛' },
    { id: 7, emoji: '🤫' },
    { id: 8, emoji: '😑' },
    { id: 9, emoji: '🙄' },
    { id: 10, emoji: '🤐' },
    { id: 11, emoji: '🤑' },
    { id: 12, emoji: '🤗' },
    { id: 13, emoji: '😏' },
    { id: 14, emoji: '🥃' },
    { id: 15, emoji: '😒' },
    { id: 16, emoji: '😪' },
    { id: 17, emoji: '😴' },
    { id: 18, emoji: '🤤' },
    { id: 19, emoji: '🤧' },
    { id: 20, emoji: '🥶' }
  ])
  const [isshow, setisshow] = useState(false)
  //控制弹窗显示隐藏
  let changelayer = () => {
    if (isshow === true) {
      setisshow(false)
    } else {
      setisshow(true)
    }
  }
  //点击某个emoji 将该emoji加入到评论框中，  不可以直接赋值  会覆盖评论框原先内容 

  const handleok = (emoji) => {
    setText(text.concat(emoji))
  }
  // let user = {
  //   _id: "65dffcd95c540000e0005ba2",
  //   friendId: "[ \"65dffcd95c540000e0005ba3\", \"65dffcd95c540000e0005ba4\" ]",
  //   password: "12138",
  //   picture: "https://tupian.qqw21.com/article/UploadPic/2014-10/20141032313469027.jpg",
  //   username: "友人A"
  // }
  // let friend = {
  //   _id: "65dffcd95c540000e0005ba3",
  //   friendId: "[ { \"$oid\" : \"65dffcd95c540000e0005ba2\" }, { \"$oid\" : \"65dffcd95c540000e0005ba6\" } ]",
  //   password: "123456",
  //   picture: "https://img0.baidu.com/it/u=3158551034,2286143108&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400\n",
  //   username: "sheniu"
  // }


  //与后端建立连接
  const socket = io('http://123.57.180.216:3000', {
    query: {
      userId: user._id,
    },
    extraHeaders: {
      "Access-Control-Allow-Origin": "*"
    }
  })
  //获取当前时间
  const showDate = (() => {
    const now = new Date()
    const y = now.getFullYear()
    const m = now.getMonth() + 1
    const d = now.getDate()
    const h = now.getHours()
    const mi = now.getMinutes()

    return y + '-' + (m < 10 ? '0' + m : m) + '-' + d + ' ' + (h < 10 ? '0' + h : h) + ':' + (mi < 10 ? '0' + mi : mi)
  })
  //发送消息主要代码
  const sendMessage = (type) => {
    switch (type) {
      case "message":
        if (!text) return Toast.info('发送内容不能为空!')
        socket.emit('send', {
          info: {
            date: showDate(),
            msg: text,
            formUsername: user.username,
            sendUsername: friend.username,
            formImg: user.picture,
            sendImg: friend.picture,
            uid: user._id + friend._id,
            sid: friend._id + user._id,
            formId: user._id,
            sendId: friend._id,
          },
          type: 'message'
        })
        setText("")
        di()
        break
      case "video":
        socket.emit('send', {
          info: {
            appId: "b35abcaea42941b8a7e775e7c29e9d99",   // 存储 App ID的状态
            channel: "video",   // 存储频道名的状态
            token: "007eJxTYOB8PjEty/7X6g1O4sI9jH5yfBYH4mYHb5wtrDahqsQ00FSBIcnYNDEpOTE10cTI0sQwySLRPNXc3DTVPNnIMtUyxdIy0VwqrSGQkaHigj8LIwMEgvisDGWZKan5DAwAauUcRQ==",   // 存储Token 的状态
          },
          type: 'video'
        })
        navigate('/exchange', { state: { title: '等待接听...', type: 'dial' } })
        break
    }
  }
  //判断是文本消息还是视频
  socket.on('receive', (data) => {
    switch (data.type) {
      case "message":
        setMessages([...messages, data.info])
        break
      case "video":
        navigate('/exchange', { state: { title: `${friend.username}来电...`, type: 'answer' } })
        break
    }
  })
  //获取聊天数据
  const getMessage = async () => {
    const { data: { code, messageList } } = await axios.post('/message', { formId: user._id, uid: (user._id + friend._id), sid: (friend._id + user._id) })
    code === 200 ? setMessages(messageList) : Toast.fail('获取信息失败')
  }

  // 一键到底
  let di=()=>{
    window.scrollTo(0,document.documentElement.scrollHeight)
  }
  useEffect(() => {
    getMessage()
  }, [])

  const [class1, setclass1] = useState(' ')
  let lahei = () => {
    Toast.info('拉黑成功，将不再收到对方消息')
    setIsVisible(false)
  }
  let chakan = () => {
    // navigate('/home/'+friend._id)
    setIsVisible(false)
  }

  return (
    <div id='dialogue'>

      <div>
        <Sticky>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px', height: "9vh", backgroundColor: '#fff' }}>
            <IconFont onClick={() => { navigate(-1) }} name='icon-arrowLeft' width='1.3em' height='1.3em'></IconFont>
            <h2>{friend.username}</h2>
            <More onClick={() => setIsVisible(!isVisible)} width='1.3em' height='1.3em' />
            <Popup
              visible={isVisible}
              style={{ height: '30%' }}
              position='bottom'
              round
              onClose={() => setIsVisible(false)}
            >
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <h3 onClick={() => { chakan() }}>查看他主页</h3>
                <h3 onClick={() => { lahei() }}>拉黑</h3>
                <h4 onClick={() => { setIsVisible(false) }}>取消</h4>
              </div>
            </Popup>
          </div>
        </Sticky>
      </div>
      <div id="content">
        {
          messages.map((item, index) => (
            <dl className={item.formId === user._id ? 'right' : 'left'} key={index}>
              {
                item.formId === user._id
                  ?
                  <div className='right'>
                    <dd >
                      <p className='pp1'>{item.msg}</p>
                      <p className='date' style={{ color: '#D5D5D5' }}>{item.date}</p>
                    </dd>
                    <dt>
                      <div style={{ width: '50px', height: '50px', borderRadius: '50%', border: '3px solid' }}>
                        <Image src={item.id === user.id ? item.sendImg : item.formImg} width={50} height={50} round />
                      </div>
                    </dt>
                  </div>

                  :
                  <div className='left'>
                    <dt>
                      <div style={{ width: '50px', height: '50px', borderRadius: '50%', border: '3px solid' }}>
                        <Image src={item.id === user.id ? item.sendImg : item.formImg} width={50} height={50} round />
                      </div>
                    </dt>
                    <dd>
                      <p className='pp2'>{item.msg}</p>
                      <p className='date' style={{ color: '#D5D5D5' }}>{item.date}</p>
                    </dd>
                  </div>
              }
            </dl>
          ))
        }

      </div>

      <div id="bottom" >

        {/* <IconFont name='icon-xiazai8' /> */}
        <IconFont name='icon-shipin' onClick={() => sendMessage('video')} />
        <Input value={text} onChange={(val) => setText(val)} style={{ width: "66vw" }} placeholder='请输入聊天内容...' />

        <Popover
          placement='top-end'
          reference={<IconFont onClick={changelayer} name='icon-biaoqing' />}
        >
          <Grid square border={false} columnNum={3} style={{ width: 240 }}>
            {
              isshow ?
                <div>
                  <div className={('layer', { hide: isshow })}>
                    {emojilist.map(item => (
                      <span key={item.id} onClick={() => handleok(item.emoji)}>{item.emoji}</span>
                    ))}
                  </div>
                </div>
                : ''
            }
          </Grid>
        </Popover>
        <IconFont onClick={() => sendMessage('message')} name='icon-huiche' />
      </div>

    </div >
  )
}
